package com.project.controller;

import com.alibaba.druid.pool.vendor.SybaseExceptionSorter;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import com.project.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    public String login(String name, String pwd, HttpServletResponse response){
        //调用业务方法，得到登陆用户
        UserBean user = service.login(name,pwd);
        if(user == null){
            return "no";
        }
        Map<String ,Object> map = new HashMap<>();
        map.put("user",user);
        response.setHeader("token", JWTUtil.getToken(map));

        return "ok";
    }

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest request){
//        UserBean user = (UserBean)request.getSession().getAttribute("loginUser");
        String token = request.getHeader("token");
        UserBean user =  (UserBean)JWTUtil.getTokenInfo(token,"user",UserBean.class);
        return user;
    }
}
